<template>
  <table-date-filter @change="onChangeDateTimeFilter" />

  <el-button
    class="bg-[var(--el-color-primary)]"
    type="primary"
    @click="downloadAllLogs"
    >{{ $t('global.action.downloadAll') }}</el-button
  >
  <el-button type="danger" class="bg-red-500" @click="deleteAllLogs">
    {{ $t('global.action.deleteAll') }}
  </el-button>

  <el-table
    ref="tableRef"
    row-key="id"
    :data="TableData"
    style="width: 100%"
    @sort-change="sortChange"
  >
    <el-table-column
      prop="id"
      label="ID"
      sortable="custom"
      width="100"
      column-key="id"
    />
    <el-table-column
      prop="interface"
      :label="$t('pageOperatingLogs.table.interface')"
      width="180"
    />
    <el-table-column
      prop="ip"
      :label="$t('pageOperatingLogs.table.ip')"
      width="180"
    />
    <el-table-column
      prop="date"
      :label="$t('pageOperatingLogs.table.time')"
      sortable="custom"
      width="180"
      column-key="date"
    />
    <el-table-column
      prop="username"
      :label="$t('pageOperatingLogs.table.user')"
      width="180"
    />
    <el-table-column
      prop="message"
      :label="$t('pageOperatingLogs.table.message')"
      width="180"
    />
    <el-table-column label="Operations">
      <template #header>
        <search-box
          ref="search"
          :placeholder="$t('pageEventLogs.table.searchLogs')"
          data-test-id="eventLogs-input-searchLogs"
        />
      </template>
    </el-table-column>
  </el-table>

  <div class="demo-pagination-block mt-8">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="perPage"
      :page-sizes="[10, 20, 30, 40]"
      :small="false"
      :disabled="false"
      :background="true"
      layout="sizes, prev, pager, next"
      :total="allLogs.length"
    />
  </div>
</template>

<script setup lang="ts">
import {
  useOperatingLogStore,
  type Log,
} from '@/store/Diagnostic/OperatingLog/OperatingLogStore';
import useDownload from '@/hooks/useDownload';
import useTableFilter from '@/hooks/useTableFilter';
import TableDateFilter from '@/components/global/TableDateFilter.vue';
import { useI18n } from 'vue-i18n';
import _ from 'lodash';

const operatingLogStore = useOperatingLogStore();
const { download } = useDownload();
const { getFilteredTableDataByDate } = useTableFilter();
const i18n = useI18n();

const search = ref();

operatingLogStore.getOperatingLogData();
const allLogs = computed(() => {
  filterLogs.value = _.cloneDeep(operatingLogStore.allOperatings);
  return _.cloneDeep(operatingLogStore.allOperatings);
});
const filterLogs = ref([] as Log[]);
const filterLogsComputed = computed(() => {
  filterLogs.value = filteredLogsByDate();
  if (search.value?.filter) {
    return filterLogs.value.filter((item) => {
      return _.includes(JSON.parse(JSON.stringify(item)), search.value.filter)
        ? true
        : false;
    });
  } else return filterLogs.value;
});

const TableData = computed(() => {
  const firstIndex = (currentPage.value - 1) * perPage.value;
  const lastIndex = currentPage.value * perPage.value;

  return filterLogsComputed.value.slice(firstIndex, lastIndex);
});

const filteredLogsByDate = () => {
  return getFilteredTableDataByDate(
    _.cloneDeep(allLogs.value),
    filterStartDate.value as Date,
    filterEndDate.value as Date,
  );
};

const filterStartDate = ref(undefined as undefined | Date);
const filterEndDate = ref(undefined as undefined | Date);

const perPage = ref(10);
const currentPage = ref(1);

const onChangeDateTimeFilter = ({
  fromDate,
  toDate,
}: {
  fromDate: ComputedRef<Date | undefined>;
  toDate: ComputedRef<Date | undefined>;
}) => {
  filterStartDate.value = fromDate.value;
  filterEndDate.value = toDate.value;
};

const downloadAllLogs = () => {
  operatingLogStore
    .download()
    .then((message: string) => {
      if (import.meta.env.MODE == 'production')
        download('audit', '/download/audit');
      else download('audit', '/api/download/audit');
      ElNotification({
        type: 'success',
        message,
      });
    })
    .catch(({ message }: any) => {
      ElNotification({
        type: 'error',
        message,
      });
    });
};

const deleteAllLogs = () => {
  ElMessageBox.confirm(
    i18n.t('pageEventLogs.modal.deleteAllMessage'),
    i18n.t('pageEventLogs.modal.deleteAllTitle'),
    {
      confirmButtonText: i18n.t('global.action.delete'),
      cancelButtonText: i18n.t('global.action.cancel'),
      type: 'warning',
    },
  )
    .then(() => {
      operatingLogStore
        .deleteAllOperatingLogs(allLogs.value)
        .then((message: string) =>
          ElNotification({
            type: 'success',
            message,
          }),
        )
        .catch(({ message }: { message: string }) =>
          ElNotification({
            type: 'error',
            message,
          }),
        );
    })
    .catch(() => {});
};

const sortChange = ({
  prop,
  order,
}: {
  column: { [index: string]: any };
  prop: string;
  order: null | 'descending' | 'ascending';
}) => {
  switch (order) {
    case 'descending':
      filterLogs.value.sort((a: any, b: any): any => {
        if (prop == 'date') {
          return b[prop].getTime() - a[prop].getTime();
        }
        return b[prop] - a[prop];
      });
      break;
    case 'ascending':
      filterLogs.value.sort((a: any, b: any): any => {
        if (prop == 'date') {
          return a[prop].getTime() - b[prop].getTime();
        }
        return a[prop] - b[prop];
      });
      break;
    default:
      filterLogs.value = _.cloneDeep(allLogs.value);
      break;
  }
};
</script>
